from micropython import const

_AFE_GAIN          	= const(0x00)
_THRESHOLD			= const(0x01)
_LIGHTNING_REG		= const(0x02)
_INT_MASK_ANT		= const(0x03)
_ENERGY_LIGHT_LSB	= const(0x04)
_ENERGY_LIGHT_MSB	= const(0x05)
_ENERGY_LIGHT_MMSB	= const(0x06)
_DISTANCE			= const(0x07)
_FREQ_DISP_IRQ		= const(0x08)
_CALIB_TRCO        	= const(0x3A)
_CALIB_SRCO        	= const(0x3B)
_RESET_LIGHT		= const(0x3C)
_CALIB_RCO         	= const(0x3D)

_OUTDOOR			= const(0x0E)

_INT_MASK			= const(0xF)
_DISTANCE_MASK     	= const(0x3F)

_NOISE_TO_HIGH     	= const(0x01)
_DISTURBER_DETECT  	= const(0x04)
_LIGHTNING         	= const(0x08)

class AS3935:
	def __init__(self, i2c_device, addr=0x01):
		self._i2c = i2c_device
		self._addr = addr
		self._i2c.writeto_mem(self._addr, _AFE_GAIN, bytes([_OUTDOOR << 1]))
		self._i2c.writeto_mem(self._addr, _INT_MASK_ANT, bytes([0x20]))		# 关闭发射机干扰的上报（因为LoRA发射模块会影响雷电检测）
		self._i2c.readfrom_mem(self._addr, _INT_MASK_ANT, 1)				# 读取一次IRQ寄存器，清除之前遗留的状态。

	def getData(self):
		data = self._i2c.readfrom_mem(self._addr, _INT_MASK_ANT, 1)
		irq = data[0] & _INT_MASK
		distance = 0
		if (irq & _LIGHTNING):
			# 读取距离
			distance = self._i2c.readfrom_mem(self._addr, _DISTANCE, 1)
			
		return distance

